package controllers

import (
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"net/http"
	"test/helpers"
	"test/models"
)

//登入
func SignInPost(c *gin.Context) {
	var (
		err  error
		user *models.User
	)
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.HTML(http.StatusOK, "auth/signin.html", gin.H{
			"message": "username or password cannot be null",
		})
		return
	}

	user, err = models.GetUserByUsername(username)

	if err != nil || user.Password != helpers.Md5(username+password) {
		c.HTML(http.StatusOK, "auth/signin.html", gin.H{
			"message": "invalid username or password",
		})
		return
	}
	//println("用户登入成功")
	//println("用户ID:" + strconv.FormatUint(uint64(user.Id), 10))

	s := sessions.Default(c)
	s.Clear()
	s.Set(SESSION_KEY, user.ID)
	s.Save()

	c.Redirect(http.StatusMovedPermanently, "/")

	/*if user.IsAdmin {
		c.Redirect(http.StatusMovedPermanently, "/admin/index")
	} else {
		c.Redirect(http.StatusMovedPermanently, "/")
	}*/

}

//注册
func SignupPost(c *gin.Context) {

	var (
		err error
		res = gin.H{}
	)

	//defer writeJSON(c, res)
	user := &models.User{
		Email: c.PostForm("email"),
		//Telephone: telephone,
		Password: c.PostForm("password"),
		IsAdmin:  true,
	}

	user.Password = helpers.Md5(user.Email + user.Password)
	err = user.Insert()
	if err != nil {
		//res["message"] = "email already exists"
		//return
		c.HTML(200, "auth/signup.html", gin.H{
			"message": "email already exists",
		})
	}
	res["succeed"] = true
	c.Redirect(301, "signin")

}

func UserIndex(c *gin.Context) {
	users, _ := models.ListUsers()
	user, _ := c.Get(CONTEXT_USER_KEY)
	c.HTML(http.StatusOK, "admin/user.html", gin.H{
		"users":    users,
		"user":     user,
		"comments": models.MustListUnreadComment(),
	})
}

func ProfileGet(c *gin.Context) {
	sessionUser, exists := c.Get(CONTEXT_USER_KEY)
	if exists {
		c.HTML(http.StatusOK, "admin/profile.html", gin.H{
			"user":     sessionUser,
			"comments": models.MustListUnreadComment(),
		})
	}
}
